package MianCalPak;

import java.io.IOException;
import java.sql.ResultSet;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import DB.DBProvider;

/**
 * Servlet implementation class UpadateUserDetails
 */
public class UpadateUserDetails extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpadateUserDetails() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//get parameters
		
		String user = (String)request.getSession().getAttribute("username");
		String pass = request.getParameter("current_password");
		String newPass = request.getParameter("password");
		String firstName = request.getParameter("first_name");
		String lastName = request.getParameter("last_name");
		String phone = request.getParameter("number");
		String op = request.getParameter("op");
		
		//check input
		
		if ((op == null && user == null) ||
			(op.toLowerCase().equals("update_password") && (pass == null&& newPass ==null)) ||
			(op.toLowerCase().equals("update_profile") && ((firstName == null) ||
														  (lastName == null) ||
														  (phone == null)))){
			
			response.sendError(HttpServletResponse.SC_BAD_REQUEST);
			return;
		}
		
		try {	
			Properties p = new Properties();
			p.load(getServletContext().getResourceAsStream("/WEB-INF/config"));
			
			DBProvider provider = new DBProvider(p);
			
			ResultSet res = provider.userDetails(user); 
			
			boolean resultFailed = (!res.next());
	
			if (resultFailed){
				response.sendError(HttpServletResponse.SC_BAD_REQUEST);
				} 
			
			if (op.toLowerCase().equals("update_profile")){
				provider.updateUserProfile(user,firstName,lastName,phone);
				response.sendRedirect("Web/profile.jsp");
			}
		
			if (op.toLowerCase().equals("update_password")){
				if (!res.getString("password").equals(pass)){
					request.getSession().setAttribute("worngPassword", pass); 
				}
				else {
					provider.updateUserPassword(user,newPass);
					request.getSession().setAttribute("passwordchanged", pass); 
				}
			}
			
			response.sendRedirect("Web/profile.jsp");
		}
		
		catch (Exception e) {
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			e.printStackTrace();} 
	}
}
